package com.topisv.tms.web.work;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXB;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springside.modules.web.Servlets;

import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.entity.EdiOrderItem;
import com.topisv.tms.entity.log.OrderLog;
import com.topisv.tms.entity.work.WorkOrder;
import com.topisv.tms.entity.work.WorkTask;
import com.topisv.tms.repository.EdiOrderDao;
import com.topisv.tms.rest.entity.md.request.RouteInfoRequestBody;
import com.topisv.tms.rest.entity.md.request.TraceDetail;
import com.topisv.tms.rest.entity.md.request.TransferBody;
import com.topisv.tms.rest.entity.md.request.TransferData;
import com.topisv.tms.rest.entity.md.request.TransferSubject;
import com.topisv.tms.rest.entity.md.request.WarehouseInfoDetail;
import com.topisv.tms.rest.entity.md.request.WarehouseInfoRequestBody;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.EdiOrderItemService;
import com.topisv.tms.service.UserService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.log.OrderLogService;
import com.topisv.tms.service.vo.invoice.MDParam;
import com.topisv.tms.service.work.WorkOrderService;
import com.topisv.tms.service.work.WorkTaskService;
import com.topisv.tms.utils.DateUtils;
import com.topisv.tms.utils.enums.StatusEnums;
//import com.topisv.tms.utils.http.SynchroShippedBatchQueue;

/**
 * 订单信息查询
 * @author ch
 *
 */
@Controller
@RequestMapping(value = "/orderMsg")
public class OrderMsgController {

	private static final Logger logger = LoggerFactory.getLogger(OrderMsgController.class);
	private static String mid_url = MDParam.URL;
	@Autowired
	private CustomersService customersService;
	@Autowired
	private AreaGroupService areaGroupService;
	@Autowired
	private WorkOrderService workOrderService;
	@Autowired
	private OrderLogService orderLogService;
	
	@Autowired
	private WorkTaskService  workTaskService;
	@Autowired
	private EdiOrderDao ediOrderDao;
	@Autowired
	private EdiOrderItemService ediOrderItemService;
	
	@Autowired
	private UserService userService;
	
	
	@RequestMapping(value="ajaxSendOutOrdeno")
	public void ajaxSendOutOrdeno(@RequestParam(value="id") Long id,HttpServletResponse response){
		JSONObject json=null;
		PrintWriter out=null;
		try {
			out=response.getWriter();
			json=new JSONObject();
			logger.info("发货接口订单id:"+id);
			WorkOrder order=this.workOrderService.loadOrderById(id);

			if(order==null){
				json.put("content", "该订单不存在");
				json.put("status", "0");
				out.print(json.toString());
				return;
			}
			if(!"finish".equals(order.getSendOutStatus())){
//				SynchroShippedBatchQueue.putSendMessageQueue("sendOutOrdeno"+StatusEnums.split.getStatus()+order.getOrder().getOrdeno());//向圆通平台创建电子面单
			}
			
			json.put("content", "重新回传中,请稍后");
			json.put("status", "1");
			out.print(json.toString());
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
		}
	}
	@RequestMapping(value="reviseWorkStatus")
	public void reviseWorkStatus(@RequestParam(value="orderNo") String orderNo,HttpServletResponse response){
		JSONObject json=null;
		PrintWriter out=null;
		try {
			out=response.getWriter();
			json=new JSONObject();
			logger.info("发货接口订单orderNo:"+orderNo);
			
			WorkOrder order=this.workOrderService.loadOrderByOrderno(orderNo);
			if(order==null){
				json.put("content", "该订单未创建批次");
				json.put("status", "0");
				out.print(json.toString());
				return;
			}
			if("cancel".equals(order.getOrder().getStatus())){
				json.put("content", "该订单已取消");
				json.put("status", "0");
				out.print(json.toString());
				return;
			}
			//key orderLog的状态码   value workOrder的状态编码 
			Map<String,String> statusMapping = new HashMap<String,String>();
			statusMapping.put("1", "1");
			statusMapping.put("2", "2");
			statusMapping.put("3", "3|9");
			statusMapping.put("4", "5");
			statusMapping.put("5", "6");
			
//			操作类型 （1.创建批次 2.创建任务  3.拣货完成 4.包装完成 5.发货完成 6.签收完成 7.异常登记 8.完成灯光拣选任务 9.打印单据 10.取消单）
			List<OrderLog> logList = this.orderLogService.loadLogByOrderno(orderNo);
			Collections.sort(logList, new Comparator<OrderLog>() {
				@Override
				public int compare(OrderLog o1, OrderLog o2) {
					return -1*(o1.getOperateType().compareTo(o2.getOperateType()));
				}
			});
			//从大到小循环
			for(OrderLog log:logList){
				if(statusMapping.containsKey(log.getOperateType())){
					String workTaskStatus = statusMapping.get(log.getOperateType());
					if(workTaskStatus.indexOf(order.getStatus())==-1){
						if("3".equals(log.getOperateType())){
							WorkTask workTask = this.workTaskService.loadTaskByCode(order.getTaskCode());
							if("lamp".equals(workTask.getPickModel())){
								order.setStatus("3");
							}else {
								order.setStatus("9");
							}
						}else {
							order.setStatus(statusMapping.get(log.getOperateType()));
						}
						this.workOrderService.save(order);
					}else {
						json.put("content", "状态正确，无需修改!");
						json.put("status", "1");
					}
					break;
				}
			}
			
			json.put("content", "修正成功!");
			json.put("status", "1");
			out.print(json.toString());
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
		}
	}
	
	@RequestMapping(value="ajaxRouteInfo")
	public void ajaxRouteInfo(@RequestParam(value="id") Long id,HttpServletResponse response){
		JSONObject json=null;
		PrintWriter out=null;
		try {
			out=response.getWriter();
			json=new JSONObject();
			logger.info("路由信息id:"+id);
			WorkOrder order=this.workOrderService.loadOrderById(id);

			if(order==null){
				json.put("content", "该订单不存在");
				json.put("status", "0");
				out.print(json.toString());
				return;
			}
			if(!"MID".equals(order.getCustomerCode()))
			{
				json.put("content", "不用回传");
				json.put("status", "0");
				out.print(json.toString());
				return;
			}
			TransferData transferData = new TransferData();
			TransferSubject transferSubject = new TransferSubject();
			transferSubject.setSender("PaiUEB");
			transferSubject.setReceiver("AnntoOMS");
			transferSubject.setDataGenerationTime(new Date());
			transferSubject.setTransferFileID(System.currentTimeMillis()+"");
			transferSubject.setDocumentType("routeInfo");
			transferSubject.setSign("");
			transferSubject.setVersion("1.0");
			RouteInfoRequestBody routeInfoRequestBody = new RouteInfoRequestBody();
			routeInfoRequestBody.setCarrierCode(order.getExpressCompany());
			routeInfoRequestBody.setCustOrdNo(order.getOrder().getCustomerOrdeno());
			routeInfoRequestBody.setExpressNo(order.getExpressNo());
			List<TraceDetail> list = new ArrayList<TraceDetail>();
			String expressCode = order.getExpressCompany();
			String expressNo= order.getExpressNo();
			String type = "";
			if("STO".equals(expressCode))
			{
				type="shentong";
			}
			else if("YTO".equals(expressCode))
			{
				type="yuantong";
			}
			else if("ZTO".equals(expressCode))
			{
				type="zhongtong";
			}
			else if("SF".equals(expressCode))
			{
				type="shunfeng";
			}
			else if("QRT".equals(expressCode))
			{
				type="zengyi";
			}
			//String url = "http://api.ickd.cn/?id=86D19B0C21EEFB0DB9D0AD5D48C6AA6E&type=json&encode=utf8&com=";
			String url = "http://api.ickd.cn/?id=110083&secret=cb16362b0de2a6514fd620819743001c&type=json&encode=utf8&com=";
			String content = pub(url+type+"&nu="+expressNo,"");
			
			if(!"".equals(content))
			{
				json = JSONObject.fromObject(content);
				String status = "";
				try {
					status = json.getString("errCode");
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if("0".equals(status))
				{
					JSONArray array = json.getJSONArray("data");
					
					for(int i=array.size()-1; i>=0; i--)
					{
						JSONObject jsonObject2 = array.getJSONObject(i); 
						String time = jsonObject2.getString("time");
						Date ftime = DateUtils.getDate(time, "yyyy-MM-dd HH:mm");
						logger.info("路由信息回传time："+time);
						logger.info("路由信息回传ftime："+ftime);
						String context = jsonObject2.getString("context");
						
						TraceDetail TraceDetail = new TraceDetail();
						TraceDetail.setActionDesc(context);
						TraceDetail.setScanTime(ftime);
						TraceDetail.setCity("");
						TraceDetail.setAction("在途");
						TraceDetail.setOperationSiteCode("");
						TraceDetail.setOperationSiteName("");
						TraceDetail.setOperator("");
						TraceDetail.setOperatorPhone("");
						TraceDetail.setOperatorPhone("");
						TraceDetail.setWeight("");
						TraceDetail.setQuestionResion("");
						TraceDetail.setQuestionType("");
						TraceDetail.setOperationSiteType("");
						TraceDetail.setSignMan("");
						TraceDetail.setExpend1("");
						TraceDetail.setExpend2("");
						TraceDetail.setExpend3("");
						TraceDetail.setExpend4("");
						TraceDetail.setExpend5("");
						list.add(TraceDetail);
					}
					routeInfoRequestBody.setTraceDetails(list);
					TransferBody transferBody = new TransferBody();
					transferBody.setContent(routeInfoRequestBody);
					transferData.setTransferBody(transferBody);
					transferData.setTransferSubject(transferSubject);
					StringWriter writer = new StringWriter();
					JAXB.marshal(transferData,writer);
					logger.info("路由信息回传："+writer.toString());
					String result = pub2(mid_url,writer.toString());
					logger.info("路由信息回传结果："+result);
				}
				else
				{
					json.put("content", "获取不到状态");
					json.put("status", "1");
					out.print(json.toString());
					return;
				}
			}
			else
			{
				json.put("content", "获取不到路由信息");
				json.put("status", "1");
				out.print(json.toString());
				return;
			}
			json.put("content", "成功");
			json.put("status", "1");
			out.print(json.toString());
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
		}
	}
	 
	@RequestMapping(value="ajaxWhInfo")
	public void ajaxWhInfo(@RequestParam(value="ordeno") String ordeno,@RequestParam(value="optype") String optype,HttpServletResponse response){
		JSONObject json=null;
		PrintWriter out=null;
		try {
			out=response.getWriter();
			json=new JSONObject();
			logger.info("仓内作业信息ordeno:"+ordeno);
			WorkOrder order=this.workOrderService.loadOrderByOrderno(ordeno);

			if(order==null){
				json.put("content", "该订单不存在");
				json.put("status", "0");
				out.print(json.toString());
				return;
			}
			if(!"MID".equals(order.getCustomerCode()))
			{
				json.put("content", "不用回传");
				json.put("status", "0");
				out.print(json.toString());
				return;
			}
			TransferData transferData = new TransferData();
			TransferSubject transferSubject = new TransferSubject();
			transferSubject.setSender("PaiUEB");
			transferSubject.setReceiver("AnntoOMS");
			transferSubject.setDataGenerationTime(new Date());
			transferSubject.setTransferFileID(System.currentTimeMillis()+"");
			transferSubject.setDocumentType("warehouseInfo");
			transferSubject.setSign("");
			transferSubject.setVersion("1.0");
			WarehouseInfoRequestBody warehouseInfoRequestBody = new WarehouseInfoRequestBody();
			warehouseInfoRequestBody.setCustOrdNo(order.getOrder().getCustomerOrdeno());
			warehouseInfoRequestBody.setWhCode(order.getOrder().getCusWarehouseCode());
			warehouseInfoRequestBody.setWhName("");
			warehouseInfoRequestBody.setCustCustomerCode(order.getOrder().getSubCustomerCode());
			List<WarehouseInfoDetail> list = new ArrayList<WarehouseInfoDetail>();
			WarehouseInfoDetail warehouseInfoDetail = new WarehouseInfoDetail();
			warehouseInfoDetail.setExpand1(ordeno);
			warehouseInfoDetail.setOperationTime(new Date());
			if("3".equals(optype))
			{
				warehouseInfoDetail.setStepName("拣货");
				warehouseInfoDetail.setNextStepName("");
			}
			else if("4".equals(optype))
			{
				warehouseInfoDetail.setStepName("复核");
				warehouseInfoDetail.setNextStepName("发货");
			}
			else if("5".equals(optype))
			{
				warehouseInfoDetail.setStepName("发货");
				warehouseInfoDetail.setNextStepName("快递交接");
			}
			else if("9".equals(optype))
			{
				warehouseInfoDetail.setStepName("打单");
				warehouseInfoDetail.setNextStepName("");
			}
			else if("1".equals(optype))
			{
				warehouseInfoDetail.setStepName("接单");
				warehouseInfoDetail.setNextStepName("");
			}
			List<OrderLog> ols = orderLogService.loadLogByOrdernoAndOperateType(ordeno, optype);
			if(null != ols && !ols.isEmpty())
			{
				warehouseInfoDetail.setOperationTime(ols.get(0).getOperateTime());
			}
			warehouseInfoDetail.setNextOperator("");
			warehouseInfoDetail.setNextOperatorInfo("");
			warehouseInfoDetail.setExpand2("");
			warehouseInfoDetail.setExpand3("");
			warehouseInfoDetail.setExpand4("");
			warehouseInfoDetail.setExpand5("");
			warehouseInfoDetail.setOperator("作业员");
			warehouseInfoDetail.setOperatorInfo("");
			
			list.add(warehouseInfoDetail);
			warehouseInfoRequestBody.setWarehouseInfoDetails(list);
			TransferBody transferBody = new TransferBody();
			transferBody.setContent(warehouseInfoRequestBody);
			transferData.setTransferBody(transferBody);
			transferData.setTransferSubject(transferSubject);
			StringWriter writer = new StringWriter();
			JAXB.marshal(transferData,writer);
			logger.info("仓内作业信息回传："+writer.toString());
			String result = pub2(mid_url,writer.toString());
			logger.info("仓内作业信息回传结果："+result);
			json.put("content", "成功");
			json.put("status", "1");
			out.print(json.toString());
		} catch (Exception e) {
			e.printStackTrace();
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
		}
	}
	
	@RequestMapping(value="v2_ajaxCreateMailOrdeno")
	public void ajaxAreaGroup(@RequestParam(value="id") Long id,HttpServletResponse response){
		JSONObject json=null;
		PrintWriter out=null;
		try {
			out=response.getWriter();
			json=new JSONObject();
			logger.info("电子面单创建订单:"+id);
			WorkOrder order=this.workOrderService.loadOrderById(id);

			if(order==null){
				json.put("content", "该订单不存在");
				json.put("status", "0");
				out.print(json.toString());
				return;
			}
			if("ebill".equals(order.getBillType())&&"YTO".equals(order.getExpressCompany())){
//				SynchroShippedBatchQueue.putSendMessageQueue("createOrdenoYTO"+StatusEnums.split.getStatus()+order.getOrder().getOrdeno());//向圆通平台创建电子面单
			}
			
			json.put("content", "正在创建");
			json.put("status", "1");
			out.print(json.toString());
			logger.info("根据商家编码获取网点信息:"+json.toString());
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
		}
	}
	
	/**
	 * 快递虚拟测试 - 输入一个快递单号并关联，默认则使用931314941227
	 * @param id
	 * @param response
	 */
	@RequestMapping(value="ajaxKuaidiSimulatorTest")
	public void ajaxKuaidiSimulatorTest(@RequestParam(value="id") Long id,@RequestParam(value="orderno",required =false) String orderno,HttpServletResponse response){
		logger.info("快递虚拟测试 : id= " + id + " orderno = " + orderno);
		if(null == orderno || "".equals(orderno)){
			orderno = "931314941227";
		}
		JSONObject json=null;
		PrintWriter out=null;
		try {
			out=response.getWriter();
			json=new JSONObject();

			WorkOrder order=this.workOrderService.loadOrderById(id);

			if(order==null){
				json.put("content", "该工作单不存在");
				json.put("status", "0");
				out.print(json.toString());
				return;
			}
			WorkOrder order2 = workOrderService.loadByOrdernoOrExpressno(orderno);
			if( null != order2){
				logger.info("快递虚拟测试 : 运单("+orderno+")被任务单("+order2.getId()+")占用,替换之");
				order2.setEbillNo(null);
				order2.setExpressNo(null);
				workOrderService.save(order2);
			}
			order.setExpressCompany("SF");
			order.setPrintStatus("printed");
			if("ebill".equals(order.getBillType())){
				order.setEbillNo(orderno);
			} else {
				order.setExpressNo(orderno);
				
			}
			workOrderService.save(order);
			json.put("status", "1");
			json.put("content", "虚拟打印和设置运单号"+orderno+"成功");
			out.print(json.toString());
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
		}
	}	

	/**
	 * 导向订单信息页面
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "v2_toOrderMsgPage")
	public String toOrderMsgPage(Model model, ServletRequest request) {
		try {
			
			//查出当前用户关联的商家列表
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			List<Customers> customerList=this.customersService.loadCustomerByAuthority(curUser);
			model.addAttribute("customerList",customerList);
			model.addAttribute("userType",curUser.userType);
			  
		} catch (Exception e) {
			logger.error("error",e);																		
		}
		return "work/msg/orderMsgList";
	}
	
	/**
	 * 查询订单信息
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "v2_queryOrderMsg")
	public String queryOrderMsg(Model model, ServletRequest request) {
		try {
			
			//查出当前用户关联的商家列表
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			List<Customers> customerList=this.customersService.loadCustomerByAuthority(curUser);
			model.addAttribute("customerList",customerList);
			model.addAttribute("userType",curUser.userType);
			
			Map<String, Object> param = Servlets.getParametersStartingWith(request, "_");
			String customerCode=(String) param.get("customerCode");
			
			//订单查询
			List<WorkOrder> orderList = this.workOrderService.loadOrder(param);
			model.addAttribute("orderList", orderList);
			model.addAttribute("param", Servlets.encodeParameterStringWithPrefix(param, "_"));
			
			//初始化仓库数据
			if(StringUtils.isNotBlank(customerCode)){
				List<AreaGroup> warehouseList=this.areaGroupService.loadAreaGroupByAuthority(curUser,customerCode);
				model.addAttribute("warehouseList", warehouseList);
			}
			  
		} catch (Exception e) {
			
			logger.error("error",e);
		}
		return "work/msg/orderMsgList";
	}
	
	
	/**
	 * 订单日志明细
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "v2_orderMsgDetail/{orderno}")
	public String orderMsgDetail(@PathVariable("orderno")String orderno,Model model) {
		try {
			
			//订单明细
			WorkOrder order=this.workOrderService.loadOrderByOrderno(orderno);
			if(null == order){
				order = new WorkOrder();
				EdiOrder ediOrder = ediOrderDao.findByOrdeno(orderno);
				order.setOrder(ediOrder);
			}
			model.addAttribute("order",order);
			
			List<EdiOrderItem> itemList = ediOrderItemService.findByOrdeno(orderno);
			model.addAttribute("itemList",itemList);
			//作业日志
			List<OrderLog> logList=this.orderLogService.loadLogByOrderno(orderno);
			model.addAttribute("logList",logList);
			
		} catch (Exception e) {
			
			logger.error("error",e);
		}
		return "work/msg/orderMsgDetail";
	}
	
	public static String pub(String serviceURL, String param) {
		URL url = null;
		HttpURLConnection connection = null;
		StringBuffer buffer = new StringBuffer();
		try {
			url = new URL(serviceURL);
			connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setUseCaches(false);
			connection.setRequestMethod("POST");
			// connection.setRequestProperty("Content-Length",param.length()+"");
			// connection.setRequestProperty("User-Agent","Java/1.6.0_29");

			OutputStream outputStream = connection.getOutputStream();
			outputStream.write(param.getBytes("UTF-8"));
			outputStream.flush();
			outputStream.close();
			InputStream inputStream = connection.getInputStream();
			byte[] bytes = new byte[1024];
			int count = inputStream.read(bytes);
			while (count != -1) {
				buffer.append(new String(bytes, 0, count, "UTF-8"));
				count = inputStream.read(bytes);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (connection != null) {
				connection.disconnect();
			}
		}
		return buffer.toString();
	}
	
	public static String pub2(String serviceURL, String param) {
		URL url = null;
		HttpURLConnection connection = null;
		StringBuffer buffer = new StringBuffer();
		try {
			url = new URL(serviceURL);
			connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setUseCaches(false);
			connection.setRequestMethod("POST");
			connection.setRequestProperty("Content-Length",param.length()+"");
			connection.setRequestProperty("Content-Type", "text/xml");
			// connection.setRequestProperty("User-Agent","Java/1.6.0_29");
			//connection.connect();
			String username = "Annto_PaiU";
	    	String password = "nDsht3^v";
	    	String input = username + ":" + password; 
	    	String encoding = getBASE64(input);   
	    	connection.setRequestProperty( "Authorization","Basic "+encoding); 
			/*OutputStream os=connection.getOutputStream();
	        DataOutputStream dos=new DataOutputStream(os);
	        dos.write(param.getBytes("UTF-8"));
	        dos.flush();
	        dos.close(); */
			OutputStream outputStream = connection.getOutputStream();
			outputStream.write(param.getBytes("UTF-8"));
			outputStream.flush();
			outputStream.close();
			InputStream inputStream = connection.getInputStream();
			byte[] bytes = new byte[1024];
			int count = inputStream.read(bytes);
			while (count != -1) {
				buffer.append(new String(bytes, 0, count, "UTF-8"));
				count = inputStream.read(bytes);
			}
			inputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (connection != null) {
				connection.disconnect();
			}
		}
		return buffer.toString();
	}
	
	public static String getBASE64(String str) {
		   String s = null;
		   if (str != null) {
		    try {
				s = new sun.misc.BASE64Encoder().encode(str.getBytes("UTF-8"));
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		  }
		  return s;
		}
	
}
